import React from 'react';
import {ImmerseScreen, StatusBarView} from "@/components/template";
import {
    ImageBackground,
    View,
    VStack,
    Image,
    Text,
    HStack,
    Input,
    InputField,
    FormControl,
    Button, ButtonText, Pressable
} from "@gluestack-ui/themed";
import {useTheme} from "@/hooks";
import {useTranslation} from "react-i18next";
import {loginChannels} from "@/theme/enums/screen";
import {Option} from "@/types/public";
import {useImmer} from "use-immer";
import {Icon, DropDownMenu, Checkbox} from "@/components/k-view";
import type {ApplicationScreenProps} from "@/types/navigation";
import useTool from "@/utils";
import {useStore} from "@/store";

const DropDownItem = (item: Option<number>): React.ReactNode => {
    return <Text py="$2" px="$3">{item.label}</Text>
}

const Login = ({navigation, route}: ApplicationScreenProps) => {
    const {t} = useTranslation(['common']);
    const {showToast} = useTool();
    const login = useStore.use.login();


    const {layout, colors} = useTheme();
    const agreementProps = {
        color: '$textLight500',
        size: "sm" as const
    }
    const [{isOpen, form, curChannel, hasAgreement}, updateData] = useImmer({
        isOpen: false,
        curChannel: `${t('common:AL')}UD`,
        hasAgreement: true,
        form: {
            account: "橙子网络",
            password: "chengzi888",
            login_channel: 2
        }
    });

    // 处理表单输入
    function handleFormChange(v: string, prop: string) {
        updateData(draft => {
            draft.form[prop] = v;
        })
    }

    // 设置下拉菜单打开状态
    function setIsOpen(v: boolean) {
        updateData(draft => {
            draft.isOpen = v;
        });
    }

    function changeHasAgreement() {
        updateData(draft => {
            draft.hasAgreement = !hasAgreement;
        })
    }

    // 跳转协议
    function jumpWebView(uri: string) {
        navigation.navigate("WebView", {
            uri
        })
    }

    // 处理频道切换
    function handleChannelChange(keys: any) {
        let index = Number(keys?.currentKey);
        let channel = loginChannels[index]
        updateData(draft => {
            draft.curChannel = channel.label;
            draft.form.login_channel = channel.value;
        })
    }

    // 处理登录
    function handleLogin() {
        if (!hasAgreement) return showToast(t('common:login.pleaseTickProtocol'), "error");
        login(form).then(res => {
            showToast(t('common:login.loginSuccess'), "success", {
                callBack: () => navigation.push('Tabbar', {screen: 'Dashboard'})
            });
        }).catch(err => {
            console.log(err, "处理失败")
        });
    }

    // 处理取消登录
    function handleCancelLogin() {
        navigation.goBack();
    }

    return (
        <ImmerseScreen>
            <ImageBackground
                resizeMode="cover"
                style={[layout.fullWidth, {height: 1864}]}
                source={require("@/theme/assets/images/login/bg-img.png")}
            >
                <StatusBarView></StatusBarView>

                <VStack
                    style={[layout.itemsCenter, layout.justifyCenter]}
                    pt="$20"
                >
                    <Image
                        width={200}
                        height={96}
                        source={require('@/theme/assets/images/login/app_name.png')}
                        alt="logo"
                    ></Image>
                    <Text
                        size="sm"
                        color="$textLight500"
                    >{t('common:login.slogan')}</Text>
                </VStack>

                <View
                    mt="$12"
                    px="$10"
                >
                    <DropDownMenu<Option<number>>
                        menus={loginChannels}
                        width={300}
                        itemRender={DropDownItem}
                        onSelectionChange={handleChannelChange}
                        onOpen={() => setIsOpen(true)}
                        onClose={() => setIsOpen(false)}
                    >
                        <HStack
                            style={[layout.itemsCenter]}
                            h={40}
                        >
                            <Text size="sm" color="$textLight500">{t('common:login.selectChannel')}:{curChannel}</Text>
                            <Icon
                                name={'\ue627'}
                                size={12}
                                color={colors.textLight500}
                                isRotate={isOpen}
                            />
                        </HStack>
                    </DropDownMenu>
                    <FormControl
                        isRequired={true}
                        isInvalid
                    >
                        <Input
                            bg="$white"
                            borderWidth={0}
                            size="xl"
                        >
                            <InputField
                                placeholder={t("common:login.accountPlaceholder")}
                                color="$textLight950"
                                value={form.account}
                                placeholderTextColor="$textLight300"
                                onChangeText={(v) => handleFormChange(v, 'account')}
                            />
                        </Input>
                        <Input
                            bg="$white"
                            borderWidth={0}
                            mt={10}
                            size="xl"
                        >
                            <InputField
                                type="password"
                                placeholder={t("common:login.pwdPlaceholder")}
                                color="$textLight950"
                                placeholderTextColor="$textLight300"
                                value={form.password}
                                onChangeText={(v) => handleFormChange(v, 'password')}
                            />
                        </Input>
                        <VStack
                            mt="$12"
                            space="md"
                        >
                            <Button bg="#8BA8F8" onPress={handleLogin}>
                                <ButtonText>{t("common:login.name")}</ButtonText>
                            </Button>
                            <Button bg="#F7F7F7" onPress={handleCancelLogin}>
                                <ButtonText color="$textLight950">{t("common:cancel")}</ButtonText>
                            </Button>
                        </VStack>
                    </FormControl>
                    <Checkbox
                        isChecked={hasAgreement}
                        mt={10}
                        onChange={changeHasAgreement}
                        aria-label="Checkbox"
                    >
                        <HStack pl="$2">
                            <Text {...agreementProps}>已阅读并同意</Text>
                            <Pressable onPress={() => jumpWebView('http://privacy.chengzicid.com/server.html')}>
                                <Text {...agreementProps} color="#8BA8F8">《服务协议》</Text>
                            </Pressable>
                            <Text {...agreementProps}>和</Text>
                            <Pressable onPress={() => jumpWebView('http://privacy.chengzicid.com/')}>
                                <Text {...agreementProps} color="#8BA8F8">《隐私协议》</Text>
                            </Pressable>
                        </HStack>
                    </Checkbox>
                </View>
            </ImageBackground>
        </ImmerseScreen>

    )
        ;
};

export default Login;